package com.jzy.message.listener;

import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.jzy.message.R;
import com.jzy.message.db.ChatMsgDao;
import com.jzy.message.db.SessionDao;
import com.jzy.message.entity.xmpp.Msg;
import com.jzy.message.entity.xmpp.Session;
import com.jzy.message.service.MsfService;
import com.jzy.message.util.xmpp.Const;
import com.jzy.message.util.xmpp.PreferencesUtils;
import com.jzy.message.util.xmpp.XmppUtil;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Type;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author baiyuliang
 */

@SuppressWarnings("static-access")
public class MsgListener implements MessageListener{

	public static String num="0";
	public static String nicheng;
	private MsfService context;
	private NotificationManager mNotificationManager;

	private Notification mNotification;
	private KeyguardManager mKeyguardManager = null;
	
	private boolean isShowNotice=false;
	
	private ChatMsgDao msgDao;
	private SessionDao sessionDao;

	private SimpleDateFormat sd=new SimpleDateFormat("MM-dd HH:mm");
	
	public MsgListener(MsfService context, NotificationManager mNotificationManager){
		this.context=context;
		this.mNotificationManager=mNotificationManager;
		mKeyguardManager = (KeyguardManager) context.getSystemService(context.KEYGUARD_SERVICE);    
		sessionDao=new SessionDao(context);
		msgDao=new ChatMsgDao(context);
	}
	
	@Override
	public void processMessage(Chat arg0, Message message) {
		try {
			Log.i("receive", "receive");
			String time=sd.format(new Date());
			Log.i("msgtime", time);
			String msgBody = message.getBody();
			if (TextUtils.isEmpty(msgBody))
				return;
			//接收者卍发送者卍消息类型卍消息内容卍发送时间
			//String[] msgs=msgBody.split(Const.SPLIT);
			String to=message.getTo().split("@")[0];//msgs[0];//接收者,当然是自己
			String from=message.getFrom().split("@")[0];//msgs[1];//发送者，谁给你发的消息
			String msgtype= message.getSubject()==null?Const.MSG_TYPE_TEXT:message.getSubject();//msgs[2];//消息类型
			String msgcontent=msgBody;//msgs[3];//消息内容
			String msgtime=time;//msgs[4];//消息时间
			if(message.getProperty("date")!=null)
			{
				msgtime=(String)message.getProperty("date");
			}
			Session session=new Session();
			session.setFrom(from);
			session.setTo(to);
			session.setNotReadCount("");//未读消息数量
			session.setTime(msgtime);
			
			if(msgtype.equals(Const.MSG_TYPE_ADD_FRIEND)){//添加好友的请求
				session.setType(msgtype);
				session.setContent(msgcontent);
				session.setIsdispose("0");
				sessionDao.insertSession(session);
			}else	if(msgtype.equals(Const.MSG_TYPE_ADD_FRIEND_SUCCESS)){//对方同意添加好友的请求
				session.setType(Const.MSG_TYPE_TEXT);
				session.setContent("我们已经是好友了，快来和我聊天吧！");
				sessionDao.insertSession(session);
				//发送广播更新好友列表
				 Intent intent=new Intent(Const.ACTION_FRIENDS_ONLINE_STATUS_CHANGE);
	        	 context.sendBroadcast(intent);
			}else if(msgtype.equals(Const.MSG_TYPE_TEXT)){//文本类型
				Msg msg=new Msg();
				msg.setToUser(to);
				msg.setFromUser(from);
				msg.setIsComing(0);
				msg.setContent(msgcontent);
				msg.setDate(msgtime);
				msg.setIsReaded("0");
				msg.setType(msgtype);
				msgDao.insert(msg);
				sendNewMsg(msg);
				showNotice(msgcontent);
				session.setType(Const.MSG_TYPE_TEXT);
				session.setContent(msgcontent);
				if(sessionDao.isContent(from, to)){//判断最近联系人列表是否已存在记录
					sessionDao.updateSession(session);
				}else{
					sessionDao.insertSession(session);
				}
			}else if(msgtype.equals(Const.MSG_TYPE_IMG)){
				Msg msg=new Msg();
				msg.setToUser(to);
				msg.setFromUser(from);
				msg.setIsComing(0);
				//msg.setContent(msgcontent);不往数据库存内容了
				msg.setDate(msgtime);
				msg.setIsReaded("0");
				msg.setType(msgtype);
				//在本地生成图片
				String FileName = String.valueOf(System.currentTimeMillis());
				String FilePath=XmppUtil.GenerateImg(msgcontent,FileName);
				msg.setBak2(FilePath);//文件名
				msgDao.insert(msg);
				sendNewMsg(msg);
				
				session.setType(Const.MSG_TYPE_TEXT);
				session.setContent("[图片]");
				if(sessionDao.isContent(from, to)){
					sessionDao.updateSession(session);
				}else{
					sessionDao.insertSession(session);
				}
			}
			else if(msgtype.equals(Const.MSG_TYPE_VOICE))
			{
				Msg msg=new Msg();
				msg.setToUser(to);
				msg.setFromUser(from);
				msg.setIsComing(0);
				//msg.setContent(msgcontent);
				msg.setDate(msgtime);
				msg.setIsReaded("0");
				msg.setType(msgtype);
				msg.setBak1(message.getThread());//时长
				//在本地生成语音
				String FileName = String.valueOf(System.currentTimeMillis());
				String FilePath=XmppUtil.GenerateVoic(msgcontent,FileName);
				msg.setBak2(FilePath);//文件名
				msgDao.insert(msg);
				sendNewMsg(msg);
				session.setType(Const.MSG_TYPE_TEXT);
				session.setContent("[语音]");
				if(sessionDao.isContent(from, to)){
					sessionDao.updateSession(session);
				}else{
					sessionDao.insertSession(session);
				}
			}
			else if(msgtype.equals(Const.MSG_TYPE_LOCATION)){//位置
				Msg msg=new Msg();
				msg.setToUser(to);
				msg.setFromUser(from);
				msg.setIsComing(0);
				msg.setContent(msgcontent);
				msg.setDate(msgtime);
				msg.setIsReaded("0");
				msg.setType(msgtype);
				msgDao.insert(msg);
				sendNewMsg(msg);
				session.setType(Const.MSG_TYPE_TEXT);
				session.setContent("[位置]");
				if(sessionDao.isContent(from, to)){
					sessionDao.updateSession(session);
				}else{
					sessionDao.insertSession(session);
				}
			}else if(msgtype.equals(Const.MSG_TYPE_CONFERENCECALL)){//视频呼叫
				Msg msg=new Msg();
				msg.setToUser(to);
				msg.setFromUser(from);
				msg.setIsComing(0);
				msg.setContent(msgcontent);
				msg.setDate(msgtime);
				msg.setIsReaded("0");
				msg.setType(msgtype);
				msgDao.insert(msg);
				sendNewMsg(msg);
				session.setType(Const.MSG_TYPE_CONFERENCECALL);
				session.setContent("视频呼叫");
				if(sessionDao.isContent(from, to)){//判断最近联系人列表是否已存在记录
					sessionDao.updateSession(session);
				}else{
					sessionDao.insertSession(session);
				}
				//开启视频呼叫界面
				/*Intent it_conference=new Intent(BaseApplication.getContext(), TelepresenceActivity.class);
				it_conference.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				it_conference.putExtra("CallNumber",msgcontent);
				BaseApplication.getContext().startActivity(it_conference);*/
			}else if(msgtype.equals(Const.MSG_TYPE_VOICECALL)){//语音呼叫
				Msg msg=new Msg();
				msg.setToUser(to);
				msg.setFromUser(from);
				msg.setIsComing(0);
				msg.setContent(msgcontent);
				msg.setDate(msgtime);
				msg.setIsReaded("0");
				msg.setType(msgtype);
				msgDao.insert(msg);
				sendNewMsg(msg);
				session.setType(Const.MSG_TYPE_VOICECALL);
				session.setContent("语音呼叫");
				if(sessionDao.isContent(from, to)){//判断最近联系人列表是否已存在记录
					sessionDao.updateSession(session);
				}else{
					sessionDao.insertSession(session);
				}
				//开启语音呼叫界面
				/*Intent it_voicecall=new Intent(BaseApplication.getContext(), CallActivity.class);
				it_voicecall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				it_voicecall.putExtra("Paras",new String[]{msgcontent,"0"});
				BaseApplication.getContext().startActivity(it_voicecall);
				BaseApplication.getContext().startActivity(new Intent(BaseApplication.getContext(), CallActivity.class).putExtra("CallNumber",msgcontent));*/
			}
			Intent intent=new Intent(Const.ACTION_ADDFRIEND);//发送广播，通知消息界面更新
			context.sendBroadcast(intent);
			//showNotice(session.getFrom()+":"+session.getContent());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	void sendNewMsg(Msg msg){
		Intent intent=new Intent(Const.ACTION_NEW_MSG);//发送广播到聊天界面
		Bundle b=new Bundle();
		b.putSerializable("msg", msg);
		intent.putExtra("msg", b);
		context.sendBroadcast(intent);
		num="1"; //表示未读
		nicheng=msg.getFromUser();//好友的手机号  进行判断 显示红点问题
	}
	public static String jian(){
		return num+"@"+nicheng;
	}
	@SuppressWarnings("deprecation")
	public void showNotice(String content) {
		// 更新通知栏
		CharSequence tickerText = content;
		mNotification = new Notification(R.drawable.ic_notice, tickerText, System.currentTimeMillis());
		mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		if(PreferencesUtils.getSharePreBoolean(context, Const.MSG_IS_VOICE)){
			// 设置默认声音
			mNotification.defaults |= Notification.DEFAULT_SOUND;
		}
		if(PreferencesUtils.getSharePreBoolean(context, Const.MSG_IS_VIBRATE)){
			// 设定震动(需加VIBRATE权限)
			mNotification.defaults |= Notification.DEFAULT_VIBRATE;
		}
		// LED灯
		mNotification.defaults |= Notification.DEFAULT_LIGHTS;
		mNotification.ledARGB = 0xff00ff00;
		mNotification.ledOnMS = 500;
		mNotification.ledOffMS = 1000;
		mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
		//mNotification.setLatestEventInfo(context, "新消息", tickerText, null);
		mNotificationManager.notify(Const.NOTIFY_ID, mNotification);// 通知
	}
	private String ConvertType(Type type)
	{
		return "";
	}
	
 }

